#! /usr/bin/python
# -*- coding: cp1250 -*-

import os
import sys
import glob
import string

# removing dependencies from pepe library in this case
# because this is good demonstration file for python beginners
# they are to be able to run it as standalone script 

#import pepe.p_txt.bigtxt as bt

class lines:
    ''' read big text file as iterator
    '''
    def __init__(self , flpath_s):
        self.flpath_s = flpath_s
        self.sfile_fl = open(flpath_s, 'r') 
    def __getitem__( self , index ):
        line_s = self.sfile_fl.readline()
        if line_s:
            return line_s
        else:
            raise IndexError

def getSample(filemask, topCount=10000):
    '''Get sample of <topCount> rows.
    '''
    for inpfile in glob.glob(filemask):

        lino = 0
        head = []
        tail = []

        output = open(string.split(inpfile, '.')[0] + '.sample.#', 'w')

        #for line in bt.lines(inpfile):
        for line in lines(inpfile):
            lino += 1
            if lino < int(topCount):
                head.append(line)
            else:
                # exit for loop
                break

        output.write("%s" % (string.join(head,'')))
        output.close()

def main(filemask):
    '''Count rows and print out TAIL and HEAD (100 rows) of text file.

    Syntax:     cht <input file mask>
    Example:    cht *.csv
    '''
    for inpfile in glob.glob(filemask):

        lino = 0
        head = []
        tail = []

        #output = open(inpfile+'.cht.#', 'w')
        
        #fname = string.split(inpfile, '.')[:]
        
        output = open(string.split(inpfile, '.')[0] + '.cht.#', 'w')

        #for line in bt.lines(inpfile):
        for line in lines(inpfile):
            lino += 1
            if lino < 100: 
                head.append(line)
                tail.append(line)
            else:
                tail.append(line)
                tail.pop(0)

        output.write("%s\n%s \t ROWS COUNT: \t%s\nHEAD:\n%s \nTAIL:\n%s" %
                     (
                      'pepe/utils/cht.py',
                      inpfile,
                      str(lino),
                      string.join(head,''),
                      string.join(tail,'')
                      )
                     )
        output.close()

if __name__ == '__main__':
    ''' '''
    if len(sys.argv) == 2:
        main(sys.argv[1])
    elif len(sys.argv) == 3:
        if sys.argv[2] in ('get-sample', 'getsample', 'sample'):
            getSample(sys.argv[1])
    else:
        print main.__doc__
